package moltencore.network.serverlobby;

import moltencore.game.*;
import moltencore.game.loader.GameCreator;
import moltencore.game.loader.exception.FieldCreationException;
import moltencore.game.loader.exception.GameCreationException;
import moltencore.network.game.GameLobby;
import moltencore.network.game.GameDemon;

import java.util.*;
import java.net.SocketException;

import moltencore.network.serverlobby.exception.LobbyCreationException;
import org.apache.log4j.Logger;

public class GameList {
	private Logger logger = Logger.getLogger(GameList.class);

	private HashMap<Integer, GameLobby> gameLobbies = new HashMap<Integer, GameLobby>();

	public int openGame(
			long hostIdentification,
			Settings settings) throws GameCreationException {
		Game game = GameCreator.createGame(settings, hostIdentification);
		// todo 
		game.teamSize = settings.isTeamsEnabled() ? 2 : 1;
		GameLobby lobby = null;
		try {
			lobby = new GameLobby(settings, GameCreator.createFields(settings));
		}
		catch(LobbyCreationException e) {
			throw new GameCreationException(e);
		}
		catch(FieldCreationException e) {
			throw new GameCreationException(e);
		}
		int gamePort;
		try {
			GameDemon gameDemon = new GameDemon(game, lobby);
			gamePort = gameDemon.getSocketPort();
			new Thread(gameDemon).start();
		}
		catch(SocketException e) {
			throw new GameCreationException("Failed to open server side connection for game", e);
		}
		gameLobbies.put(gamePort, lobby);
		return gamePort;
	}

	public Collection<GameData> listOpenGames() {
		LinkedList<GameData> openGames = new LinkedList<GameData>();
		for(Map.Entry<Integer, GameLobby> lobbyEntry : gameLobbies.entrySet()) {
			GameLobby lobby = lobbyEntry.getValue();
			openGames.add(new GameData(lobby.getSettings(), lobby.getPlayers().getOnlinePlayers().size(), lobbyEntry.getKey()));
		}
		return openGames;
	}
}
